package com.ruoyi.mentor.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.ExamineStatusConstants;
import com.ruoyi.common.constant.UserTypeConstants;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.mentor.domain.Instructor;
import com.ruoyi.mentor.domain.Student;
import com.ruoyi.mentor.domain.StudentDetail;
import org.apache.xmlbeans.impl.xb.xmlconfig.Usertypeconfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.mentor.bo.ExamineAddBo;
import com.ruoyi.mentor.bo.ExamineQueryBo;
import com.ruoyi.mentor.bo.ExamineEditBo;
import com.ruoyi.mentor.domain.Examine;
import com.ruoyi.mentor.mapper.ExamineMapper;
import com.ruoyi.mentor.vo.ExamineVo;
import com.ruoyi.mentor.service.IExamineService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 审核信息Service业务层处理
 *
 * @author LH
 * @date 2021-05-22
 */
@Service
public class ExamineServiceImpl extends ServiceImpl<ExamineMapper, Examine> implements IExamineService {

    @Autowired
    StudentServiceImpl studentService;

    @Autowired
    InstructorServiceImpl instructorService;

    @Autowired
    MailServiceImpl mailService;

    @Autowired
    StudentDetailServiceImpl studentDetailService;

    @Override
    public ExamineVo queryById(Long id){
        return getVoById(id, ExamineVo.class);
    }

    @Override
    public TableDataInfo<ExamineVo> queryPageList(ExamineQueryBo bo) {
        PagePlus<Examine, ExamineVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), ExamineVo.class);
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<ExamineVo> queryList(ExamineQueryBo bo) {
        return listVo(buildQueryWrapper(bo), ExamineVo.class);
    }

    private LambdaQueryWrapper<Examine> buildQueryWrapper(ExamineQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Examine> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getExamineAdminName()), Examine::getExamineAdminName, bo.getExamineAdminName());
        lqw.like(StrUtil.isNotBlank(bo.getExamineUserName()), Examine::getExamineUserName, bo.getExamineUserName());
        lqw.eq(bo.getUserType() != null, Examine::getUserType, bo.getUserType());
        lqw.eq(bo.getIsSuccess() != null, Examine::getIsSuccess, bo.getIsSuccess());
        lqw.eq(StrUtil.isNotBlank(bo.getMessage()), Examine::getMessage, bo.getMessage());
        lqw.eq(bo.getCreateDate() != null, Examine::getCreateDate, bo.getCreateDate());
        lqw.eq(bo.getUpdateDate() != null, Examine::getUpdateDate, bo.getUpdateDate());
        lqw.eq(bo.getIsDeleted() != null, Examine::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    @Override
    public Boolean insertByAddBo(ExamineAddBo bo) {
        Examine add = BeanUtil.toBean(bo, Examine.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean updateByEditBo(ExamineEditBo bo) {
        Examine update = BeanUtil.toBean(bo, Examine.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Examine entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

    /**
     * 审核
     * @param adminName
     * @param status
     * @param studentId
     * @param message
     */
    @Transactional
    @Override
    public void examine(String adminName, Integer status, Long studentId, String message) {
        Student student = studentService.getById(studentId);
        StudentDetail studentDetail = studentDetailService.getOne(new QueryWrapper<StudentDetail>().eq("stu_id", studentId));
        if (!status.equals(ExamineStatusConstants.EXAMINE_SUCCESS)&&!status.equals(ExamineStatusConstants.EXAMINE_ERROR)){
            throw new CustomException("审核状态出错");
        }
        student.setExamineStatus(status);
        studentService.updateById(student);

        Examine examine = new Examine();
        examine.setSiId(studentId);
        examine.setUserType(UserTypeConstants.ROLE_STUDENT);
        examine.setExamineAdminName(adminName);
        examine.setExamineUserName(student.getStuName());

        //找出之前审核未通过的记录，将is_success字段改成成功1
        Examine one = getOne(new QueryWrapper<Examine>().eq("is_success", 0).eq("si_id", studentId));
        if (one!=null){
            one.setIsSuccess(1);
            updateById(one);
        }

        if (status==ExamineStatusConstants.EXAMINE_SUCCESS){
            examine.setIsSuccess(1);
            if (studentDetail!=null&&studentDetail.getStuEmail()!=null){
                mailService.sendExamineSuccessMail(studentDetail.getStuEmail());
            }
        }else {
            if (studentDetail!=null&&studentDetail.getStuEmail()!=null){
                mailService.sendExamineFailMail(studentDetail.getStuEmail(),message);
            }
            examine.setIsSuccess(0);
        }


        examine.setMessage(message);
        save(examine);

    }

    @Override
    public Examine getExamineMsg(Integer type, Long id) {
        Examine examine = getOne(new QueryWrapper<Examine>().eq("user_type", type).eq("is_success", 0).eq("si_id",id));
        if (examine==null){
            throw new CustomException("获取审核状态失败");
        }
        return examine;
    }

    @Override
    public void examineInstructor(String adminName, Integer status, Long insId, String message) {
        Instructor instructor = instructorService.getById(insId);
        if (!status.equals(ExamineStatusConstants.EXAMINE_SUCCESS)&&!status.equals(ExamineStatusConstants.EXAMINE_ERROR)){
            throw new CustomException("审核状态出错");
        }
        instructor.setExamineStatus(status);
        instructorService.updateById(instructor);

        Examine examine = new Examine();
        examine.setSiId(insId);
        examine.setUserType(UserTypeConstants.ROLE_INSTRUCTOR);
        examine.setExamineAdminName(adminName);
        examine.setExamineUserName(instructor.getInsName());

        //找出之前审核未通过的记录，将is_success字段改成成功1
        Examine one = getOne(new QueryWrapper<Examine>().eq("is_success", 0).eq("si_id", insId));
        if (one!=null){
            one.setIsSuccess(1);
            updateById(one);
        }

        if (status==ExamineStatusConstants.EXAMINE_SUCCESS){
            examine.setIsSuccess(1);
            if (instructor.getInsEmail()!=null){
                mailService.sendExamineSuccessMail(instructor.getInsEmail());
            }
        }else {
            examine.setIsSuccess(0);
            if (instructor.getInsEmail()!=null){
                mailService.sendExamineFailMail(instructor.getInsEmail(),message);
            }
        }

        examine.setMessage(message);
        save(examine);
    }

}
